package com.dd.admin.controller.organization;

import cn.dev33.satoken.annotation.SaIgnore;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dd.common.convert.SysPositionConvert;
import com.dd.common.dto.system.position.SysPositionDTO;
import com.dd.common.dto.system.position.SysPositionQueryDTO;
import com.dd.common.entity.SysPosition;
import com.dd.common.enums.ErrorEnum;
import com.dd.common.exception.BusinessException;
import com.dd.common.pojo.dto.PageDTO;
import com.dd.common.pojo.dto.group.CreateGroup;
import com.dd.common.service.SysPositionService;
import com.dd.common.utils.AjaxResult;
import com.dd.common.utils.PageResult;
import com.dd.common.validator.annotation.IDMust;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author cheng
 */
@SaIgnore
@Tag(name = "职位管理")
@Validated
@RequestMapping("/org/position")
@RestController
public class SysPositionController {
    @Resource
    private SysPositionService sysPositionService;
    @Resource
    private SysPositionConvert sysPositionConvert;

    @Operation(summary = "职位新增", requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
            description = "职位数据",
            required = true,
            content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = SysPositionDTO.class))
    ))
    @PostMapping("/add")
    public AjaxResult<?> add(@Validated(CreateGroup.class) @RequestBody SysPositionDTO dto) {
        this.checkPositionCode(dto.getCode());
        return AjaxResult.success(sysPositionService.save(sysPositionConvert.dtoToEntity(dto)));
    }

    @Operation(summary = "职位编辑", requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
            content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = SysPositionDTO.class))
    ))
    @PatchMapping("/edit")
    public AjaxResult<?> edit(@Validated SysPositionDTO dto) {
        this.checkPositionCode(dto.getCode());
        return AjaxResult.success(sysPositionService.updateById(sysPositionConvert.dtoToEntity(dto)));
    }

    @Operation(summary = "职位删除", parameters = @Parameter(name = "id", in = ParameterIn.PATH, description = "职位ID"))
    @DeleteMapping("/delete/{id}")
    public AjaxResult<?> delete(@PathVariable @Validated @IDMust Long id) {
        return AjaxResult.success(sysPositionService.removeById(id));
    }

    @Operation(summary = "职位详情", parameters = @Parameter(name = "id", in = ParameterIn.PATH, description = "职位ID"))
    @GetMapping("/detail/{id}")
    public AjaxResult<?> detail(@PathVariable @Validated @IDMust Long id) {
        return AjaxResult.success(sysPositionService.getById(id));
    }

    @Operation(summary = "职位列表")
    @GetMapping("/list")
    public AjaxResult<?> list(@Validated SysPositionQueryDTO dto) {
        LambdaQueryWrapper<SysPosition> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dto.getStatus() != null, SysPosition::getStatus, dto.getStatus())
                .like(StringUtils.hasText(dto.getName()), SysPosition::getName, dto.getName())
                .like(StringUtils.hasText(dto.getCode()), SysPosition::getCode, dto.getCode())
                .eq(dto.getCategory() != null, SysPosition::getCategory, dto.getCategory())
                .eq(dto.getLevel() != null, SysPosition::getLevel, dto.getLevel())
                .orderByAsc(SysPosition::getLevel);
        return AjaxResult.success(sysPositionService.list(queryWrapper));
    }

    @Operation(summary = "职位分页列表")
    @GetMapping("/page")
    public AjaxResult<?> page(@Validated PageDTO pageDTO, @Validated SysPositionQueryDTO dto) {
        Page<SysPosition> page = Page.of(pageDTO.getCurrent(), pageDTO.getSize());
        LambdaQueryWrapper<SysPosition> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dto.getStatus() != null, SysPosition::getStatus, dto.getStatus())
                .like(StringUtils.hasText(dto.getName()), SysPosition::getName, dto.getName())
                .like(StringUtils.hasText(dto.getCode()), SysPosition::getCode, dto.getCode())
                .eq(dto.getCategory() != null, SysPosition::getCategory, dto.getCategory())
                .eq(dto.getLevel() != null, SysPosition::getLevel, dto.getLevel())
                .orderByAsc(SysPosition::getLevel);
        IPage<SysPosition> result = sysPositionService.page(page, queryWrapper);
        return AjaxResult.success(PageResult.iPageHandle(result.getTotal(), result.getCurrent(), result.getSize(), result.getRecords()));
    }

    /**
     * 检查职位编码是否已存在
     *
     * @param code 职位编码
     */
    private void checkPositionCode(String code) {
        if (sysPositionService.getOne(new LambdaQueryWrapper<>(SysPosition.class).eq(code != null, SysPosition::getCode, code)) != null) {
            throw new BusinessException(ErrorEnum.DATA_EXISTS, "职位编码已存在");
        }
    }
}
